<template>
  <view>
    <!-- 由父组件控制显示 -->
    <view v-if="show">
      <!-- 蒙层 -->
      <view class="picker-mask" @click="cancel"></view>
      <!-- 底部弹窗 -->
      <view class="picker-modal">
        <view class="picker-actions">
          <view class="picker-btn" @click="cancel">取消</view>
          <view class="picker-btn confirm" @click="confirm">确定</view>
        </view>
        <picker-view
          :value="pickerValue"
          indicator-style="height: 92rpx;"
          @change="onChange"
          class="picker-view"
        >
          <picker-view-column>
            <view v-for="(item, idx) in dateOptions" :key="idx" class="picker-item">{{ item }}</view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="(item, idx) in hourOptions" :key="idx" class="picker-item">{{ item }}</view>
          </picker-view-column>
          <picker-view-column>
            <view v-for="(item, idx) in minuteOptions" :key="idx" class="picker-item">{{ item }}</view>
          </picker-view-column>
        </picker-view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "dateTimePicker",
  props: {
    show: {
      type: Boolean,
      default: false
    },
    defaultTime: {
      type: [Date, String, Number],
      default: null
    }
  },
  data() {
    return {
      pickerValue: [0, 0, 0],
      dateOptions: [],
      hourOptions: [],
      minuteOptions: [],
      displayValue: '请选择时间'
    };
  },
  created() {
    this.initOptions();
    this.initDefaultValue();
  },
  methods: {
    initOptions() {
      // 日期
      const dateArr = ['今天', '明天', '后天'];
      const now = new Date();
      for (let i = 3; i < 30; i++) {
        const d = new Date(now);
        d.setDate(now.getDate() + i);
        const mm = (d.getMonth() + 1).toString().padStart(2, '0');
        const dd = d.getDate().toString().padStart(2, '0');
        dateArr.push(`${mm}月${dd}日`);
      }
      this.dateOptions = dateArr;

      // 小时
      const hourArr = [];
      for (let i = 0; i < 24; i++) {
        if (i < 6) hourArr.push(`凌晨${i}点`);
        else if (i < 12) hourArr.push(`早上${i}点`);
        else if (i < 18) hourArr.push(`下午${i}点`);
        else hourArr.push(`晚上${i}点`);
      }
      this.hourOptions = hourArr;

      // 分钟
      const minuteArr = [];
      for (let i = 0; i <= 50; i += 10) {
        minuteArr.push(`${i.toString().padStart(2, '0')}分`);
      }
      this.minuteOptions = minuteArr;
    },
    initDefaultValue() {
      // 计算默认时间
      let date = null;
      if (this.defaultTime) {
        date = new Date(this.defaultTime);
      } else {
        date = new Date();
        date.setMinutes(date.getMinutes() + 10);
      }
      // 计算dateOptions索引
      let dIdx = 0;
      const now = new Date();
      const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      const target = new Date(date.getFullYear(), date.getMonth(), date.getDate());
      const diffDay = Math.round((target - today) / (24 * 60 * 60 * 1000));
      dIdx = diffDay >= 0 && diffDay < this.dateOptions.length ? diffDay : 0;
      // 计算hourOptions索引
      let hIdx = date.getHours();
      // 计算minuteOptions索引
      let mIdx = 0;
      const minute = date.getMinutes();
      for (let i = 0; i < this.minuteOptions.length; i++) {
        const m = parseInt(this.minuteOptions[i]);
        if (minute <= m) {
          mIdx = i;
          break;
        }
      }
      this.pickerValue = [dIdx, hIdx, mIdx];
    },
    onChange(e) {
      this.pickerValue = e.detail.value;
    },
    cancel() {
      this.pickerValue = [0, 0, 0];
      this.initDefaultValue()
      this.$emit('update:show', false);
    },
    confirm() {
      const [d, h, m] = this.pickerValue;
      this.displayValue = `${this.dateOptions[d]} ${this.hourOptions[h]} ${this.minuteOptions[m]}`;
      // 计算选中日期
      const now = new Date();
      let dateObj = new Date(now.getFullYear(), now.getMonth(), now.getDate());
      dateObj.setDate(dateObj.getDate() + d);
      dateObj.setHours(h);
      // 取分钟文本
      let minuteText = this.minuteOptions[m];
      let minute = 0;
      if (minuteText) {
        minute = parseInt(minuteText);
      }
      dateObj.setMinutes(minute);
      dateObj.setSeconds(0);
      // 格式化
      const pad = n => n.toString().padStart(2, '0');
      const formatStr = `${dateObj.getFullYear()}-${pad(dateObj.getMonth()+1)}-${pad(dateObj.getDate())} ${pad(dateObj.getHours())}:${pad(dateObj.getMinutes())}:00`;
      this.$emit('change', {
        date: this.dateOptions[d],
        hour: this.hourOptions[h],
        minute: this.minuteOptions[m],
        value: [d, h, m],
        dateTime: formatStr
      });
      this.$emit('update:show', false);
    }
  }
};
</script>

<style scoped>
.picker-mask {
  position: fixed;
  left: 0; 
  right: 0; 
  top: 0; 
  bottom: 0;
  background: rgba(0,0,0,0.3);
  z-index: 9998;
}
.picker-modal {
  position: fixed;
  left: 0; 
  right: 0; 
  bottom: 0;
  z-index: 9999;
  overflow: hidden;
  background-color: #F5F5F6;
  border-radius: 50rpx 50rpx 0 0;
  transition: all 0.3s ease;
}
.picker-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100rpx;
  background: #FFFFFF;
  padding: 0 30rpx;
}
.picker-btn {
  background: none;
  border: none;
  font-weight: 400;
  font-size: 28rpx;
  color: #999999;
}
.picker-btn.confirm {
  font-weight: 400;
  font-size: 28rpx;
  color: #FF7937;
}
.picker-view {
  width: 100%;
  height: 460rpx;
  background: #fff;
  box-sizing: border-box;
}
.picker-item {
  height: 92rpx;
  line-height: 92rpx;
  padding-left: 56rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  color: #0B1F20;
  font-weight: 500;
}
</style> 